package com.project;

import com.project.config.MVCConfig;

import com.project.filter.CharFilter;

import com.project.filter.LoginFilter;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

public class ForumMain {
    /**(一共2个方法)
     * 1构造方法：完成tomcat初始化、前端控制器注册
     */
        public ForumMain(){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);// 设置Tomcat端口
        tomcat.getConnector();// 引导HTTP引擎Context
        //定义WEB上下文
        Context context = tomcat.addContext("", null);//定义上下文
            //post文件上传过滤器
            this.registerFilter(new CharFilter(),"/*",context);

            this.registerFilter(new LoginFilter(),"/discuss/add",context);



            try {
            //创建DispatcherServlet前端控制器
            WebApplicationContext webContext = this.createApplicationContext(
                    context.getServletContext());
            DispatcherServlet dispatcherServlet =
                    new DispatcherServlet(webContext);
            //注册前端控制器
            Wrapper servletWrapper =  Tomcat.addServlet(
                    context, "dispatcherServlet", dispatcherServlet);
            servletWrapper.setLoadOnStartup(0);
            servletWrapper.addMapping("/*");


            tomcat.start();//启动tomcat
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 3.注册过滤器
     */
    private void registerFilter(Filter filter, String urlPattern, Context context){
        FilterDef fd1=new FilterDef();
        fd1.setFilter(filter);//设置过滤器
        fd1.setFilterName(filter.getClass().getSimpleName());//设置过滤器名称

        FilterMap fm1=new FilterMap();
        fm1.setFilterName(filter.getClass().getSimpleName());
        fm1.addURLPattern(urlPattern);//设置过滤器范围

        context.addFilterDef(fd1);
        context.addFilterMap(fm1);
    }
    /**
     * 2.mvc配置类注册
     * @param servletContext
     * @return
     */
    public static WebApplicationContext createApplicationContext(
            ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx
                = new AnnotationConfigWebApplicationContext();
        //注册配置类
        ctx.register(MVCConfig.class);

        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    public static void main(String[] args) {
        new ForumMain();
    }
}
